<template>
  <div class="params-contain">
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 警示框区域 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon
      >
      </el-alert>
      <el-row>
        <el-col>
          <span class="cate">选择商品分类:</span>
          <el-cascader
            :options="cateList"
            :props="cateProps"
            v-model="selectKey"
            clearable
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 动态参数区域 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isDisabled"
            @click="showAddDialog"
            >添加参数</el-button
          >
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  @close="handleClose(index, scope.row)"
                  v-for="(items, index) in scope.row.attr_vals"
                  :key="index"
                  >{{ items }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性区域 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isDisabled"
            @click="showAddDialog"
            >添加属性</el-button
          >
          <el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  @close="handleClose(index, scope.row)"
                  v-for="(items, index) in scope.row.attr_vals"
                  :key="index"
                  >{{ items }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数和属性的对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="dialogVisibleAdd"
      @close="resetForm"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleAdd = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑的对话框 -->
    <el-dialog :title="'修改' + titleText" :visible.sync="dialogVisibleEdit">
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleEdit = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    this.getCateList()
  },
  data() {
    return {
      // 商品分类列表数据
      cateList: [],
      // 层级选择器数据如何展示
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover',
        checkStrictly: true
      },
      // tab栏中活跃的名字
      activeName: 'many',
      // 选中者的ID值
      selectKey: [],
      // 动态参数表格数据
      manyTableData: [],
      // 静态属性表格数据
      onlyTableData: [],
      // 添加参数和属性的对话框是否显示
      dialogVisibleAdd: false,
      // 添加对话框中的表单数据
      addForm: {},
      // 添加对话框的表单验证规则
      addFormRules: {
        attr_name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
      },
      // 编辑对话框中的表单数据
      editForm: {
        attr_name: '',
        attr_id: 0,
        attr_vals: ''
      },
      // 编辑对话框的表单验证规则
      editFormRules: {
        attr_name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
      },
      // 编辑对话框是否显示
      dialogVisibleEdit: false
    }
  },
  methods: {
    // 获取商品分类列表数据
    async getCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: {
          type: 3,
          pagenum: '',
          pagesize: ''
        }
      })
      console.log(res.data)
      this.cateList = res.data
    },
    // 监听层级选择器改变
    handleChange() {
      // 如果用户选择的不是三级分类
      console.log(this.selectKey)
      if (this.selectKey.length === 3) {
        this.getParamsList()
      } else {
        this.manyTableData = []
        this.onlyTableData = []
        this.selectKey = []
      }
    },
    // 获取动态参数和静态属性列表数据
    async getParamsList() {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: {
            sel: this.activeName
          }
        }
      )
      console.log(res.data)
      // 将获取到的数据中的attr_vals字符串转换为数组
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // console.log(item.attr_vals)
        // 增加这两者属性是为了避免不同行tag之间的相互干扰
        item.inputVisible = false
        item.inputValue = ''
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取动态参数列表数据失败')
      }
      if (this.activeName === 'many') {
        this.manyTableData = res.data
        // console.log(this.manyTableData)
      } else if (this.activeName === 'only') {
        this.onlyTableData = res.data
      }
    },
    // 监听tab栏改变
    handleTabClick() {
      // console.log(this.activeName)
      this.handleChange()
    },
    // 监听添加参数和属性的对话框
    showAddDialog() {
      this.dialogVisibleAdd = true
    },
    // 添加动态参数和静态属性
    addParams() {
      this.$refs.addFormRef.validate(async valid => {
        console.log(valid)
        if (!valid) return
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName,
            attr_vals: this.addForm.attr_vals
          }
        )
        // console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error('添加失败')
        }
        this.$message.success('添加成功')
        this.dialogVisibleAdd = false
        this.getParamsList()
      })
    },
    // 重置表单数据
    resetForm() {
      this.$refs.addFormRef.resetFields()
    },
    // 监听编辑对话框
    showEditDialog(editRow) {
      this.dialogVisibleEdit = true
      console.log(editRow)
      this.editForm.attr_name = editRow.attr_name
      this.editForm.attr_id = editRow.attr_id
      this.editForm.attr_vals = editRow.attr_vals
    },
    // 编辑动态参数和静态属性
    editParams() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName,
            attr_vals: this.editForm.attr_vals.join(' ')
          }
        )
        // console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('更新失败')
        }
        this.$message.success(res.meta.msg)
        this.getParamsList()
        this.dialogVisibleEdit = false
      })
    },
    // 保存参数数据
    async saveParams(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: this.activeName,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('更新失败')
      }
      this.$message.success(res.meta.msg)
    },
    // 删除动态参数和静态属性
    deleteParams(pId) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          const { data: res } = await this.$http.delete(
            `categories/${this.cateId}/attributes/${pId}`
          )
          if (res.meta.status !== 200) {
            return this.$message.error('删除失败')
          }
          this.getParamsList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    handleInputConfirm(row) {
      console.log(row)

      // 当用户在文本框中按下enter键或者焦点离开时都会触发执行
      // 判断用户在文本框中输入的内容是否合法
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue)
      this.saveParams(row)
      row.inputVisible = false
    },
    // 监听添加tag按钮式触发
    showInput(row) {
      console.log(row)
      row.inputVisible = true
      row.inputValue = ''
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    // 关闭tag时触发
    handleClose(index, row) {
      // console.log(index)
      row.attr_vals.splice(index, 1)
      this.saveParams(row)
    }
  },
  computed: {
    // 按钮是否禁用
    isDisabled() {
      if (this.selectKey.length === 3) {
        return false
      } else {
        return true
      }
    },
    // 获取选中三级分类的id
    cateId() {
      if (this.selectKey.length === 3) {
        return this.selectKey[this.selectKey.length - 1]
      } else {
        return null
      }
    },
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.el-alert {
  margin-bottom: 15px;
}
.cate {
  margin-right: 10px;
}
.el-table {
  margin-top: 15px;
}
.el-tag {
  margin: 0px 15px 10px 0;
}
.input-new-tag {
  width: 120px;
}
</style>
